<?php


namespace App\Services;
use App\Models\Database as DatabaseModel;
use App\Providers\DatabaseProvider;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class Database
{
    use SoftDeletes;
    const EXSISTS = "HY000";
    private static $error = '';
    /**
     * @return string
     */
    static function error() {
        return self::$error;
    }

    static function getRandStr($length){
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str)-1;
        $randstr = '';
        for ($i=0;$i<$length;$i++) {
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    /**
     * 创建数据库
     * @param $name
     * @param $local
     * @return bool
     */
    static function create($info) {

        // 创建本地数据库
        if ($info['local'] == 1) {
            $info['db_prefix'] = $info['user_id'];
            $condition = ['user_id' => $info['user_id'], 'db_name' => $info['db_name']];
            if (DatabaseModel::where($condition)->first()) {
                self::$error = '数据库已存在';
                return false;
            }
        }
        unset($info['local']);
        $info['key']    = self::getRandStr(10);
        $newDB = DatabaseModel::create($info);
        DatabaseModel::where('user_id', $newDB->user_id)->update(['default'=>0]);
        $newDB->default  = 1;
        $newDB->save();

        DBAPP::set_database($newDB->user_id, 'mysql');  // 切换数据库
        $res = self::create_db_action($newDB);
        if (!$res) {
            $newDB->delete();
            return false;
        }
        return $newDB;
    }

    /**
     * @param $dbInfo
     * @return bool
     */
    static function create_db_action($dbInfo) : bool {
        $defaultDB      = DB::getDefaultConnection();
        $defaultHost    = config('database')['connections'][$defaultDB]['host'];
        $dbName         = $dbInfo->db_name;
        if ($dbInfo->db_host == $defaultHost) {
            try {
                Schema::createDatabase($dbName);
            } catch (\Exception $e) {
                $code = $e->getCode();
                if ($code == self::EXSISTS) {
                    self::$error = '数据库已存在';
                }
                return false;
            }
        } else {
            try {
                DBAPP::schema()->createDatabase($dbName);

            } catch (\Exception $e) {
                $code = $e->getCode();
                if ($code == self::EXSISTS) {
                    self::$error = '数据库已存在';
                }
                return false;
            }
        }
        return true;
    }

    static function update($id, $info) {

    }

    static function delete($userId, $id) {
        // 检查删除的是否是默认的
        $dbInfo = DatabaseModel::where('user_id', $userId)->where('id', $id)->first(); // 为什么要多加一层userId, 是因为杜绝删除别人的数据
        if ($dbInfo) {

            $default = $dbInfo->default;
            $dbInfo->delete();
            \App\Models\Table::where('db_id', $id)->delete();
            // 将最新的设置为默认的
            if ($default) {
                $db = DatabaseModel::where('user_id', $userId)->orderBy('id', 'desc')->first();
                if ($db) {
                    $db->default = 1;
                    $db->save();
                }
            }
        }
    }

    /**
     * @param $userId
     * @return mixed
     */
    static function search($userId) : Collection {
        $databases = DatabaseModel::where('user_id', $userId)->select(
                'id', 'key', 'local', 'name', 'default', 'driver', 'db_host', 'db_name',
                'db_user', 'db_charset', 'db_collation', 'table_prefix')->get();
        return $databases;
    }


    static function set_default($userId, $id) {
        DatabaseModel::where('user_id', $userId)->update(['default' => 0]);
        DatabaseModel::where('id', $id)->update(['default' => 1]);
    }
}
